package cloud.shyidong.core.config;

import cloud.shyidong.core.Result;
import cloud.shyidong.core.exception.BusinessException;
import cloud.shyidong.core.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

/**
 * @Description TODO
 * @Author syd
 * @Date 2023/3/28
 */
@RestControllerAdvice
@Slf4j
public class ResultResponseBodyAdvice implements ResponseBodyAdvice {
    
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return converterType.isAssignableFrom(MappingJackson2HttpMessageConverter.class);
    }
    
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            return Result.ofData(null);
        }
        if (body instanceof Result) {
            return body;
        }
        return Result.ofData(body);
    }
    
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BindException.class)
    public Result bindException(BindException bindException) {
        log.error(bindException.getMessage(), bindException);
        List<ObjectError> objectErrors = bindException.getAllErrors();
        if (CollectionUtils.isNotEmpty(objectErrors)) {
            for (ObjectError objectError : objectErrors) {
                return Result.ofErrors(BusinessException.from(objectError.getDefaultMessage()));
            }
        }
        log.error("bindException >>> {}", bindException.getMessage());
        return Result.ofData(null);
    }
    
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BusinessException.class)
    public Result businessException(BusinessException businessException) {
        log.error(businessException.getMessage(), businessException);
        return Result.ofErrors(businessException);
    }
    
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public Result exception(Exception exception) {
        log.error(exception.getMessage(), exception);
        return Result.ofErrors(BusinessException.from(exception));
    }
    
}
